package com.itany.shop.filter;

import com.itany.shop.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author MissChen
 * @date 2024年05月17日 14:07
 */
// @WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String path=request.getServletPath();
        System.out.println(path);
        if(path.endsWith(".user") || "/jsp/login.jsp".equals(path)||"/jsp/register.jsp".equals(path)||"/jsp/main.jsp".equals(path)||"findAll.product".equals(path)||"/index.jsp".equals(path)||"/showCode".equals(path)||"/js/jquery-3.4.1.js".equals(path)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //如果是其他请求，则判断是否登录
        User user= (User) request.getSession().getAttribute("user");
        if(user==null){
            //如果没有取到user，说明用户尚未登录
            request.setAttribute("loginMsg","您尚未登录，请先登录");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }
        // 如果取到了user,说明已经登录，直接放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
